//
//  BC_BoardController.m
//  CocOth
//
//  Created by BrunoCausse on 04/11/10.
//  Copyright 2010-2013 poulailler cie. All rights reserved.
//

#import "BC_BoardController.h"
#import "NSFileManager+DirectoryLocations.h"

#import "BC_Const.h"
#import "BC_BoardView.h"
#import "BC_Board.h"
#import "BC_Move.h"

#import "BC_GameTreeController.h"
#import "CocOthAppController.h"




NSString * const BC_design2DKey = @"design2D";
NSString * const BC_ShowHideCoord = @"ShowHideCoord";



@implementation BC_BoardController

@dynamic board;

- (BC_Board *)board
{
	return board;
}

- (void)setBoard:(BC_Board *)newBoard
{
	[newBoard retain];
	[board release];
	
	board = newBoard;
	
	[self needsDisplay];
}


+ (void)initialize
{
	NSMutableDictionary *defaultValues = [NSMutableDictionary dictionary];
	
	[defaultValues setObject:@"default" forKey:BC_design2DKey];
	[defaultValues setObject:[NSNumber numberWithBool:NO] forKey:BC_ShowHideCoord];
	
	[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
	
}

- (id)init
{
	self = [super init];
	if(self) {
		board = [[BC_Board alloc] init];
		[boardView setNeedsDisplay:YES];
		
	}
	return self;
}

- (void)dealloc
{
	[board release];
	[super dealloc];
}

- (void)awakeFromNib
{
	
	
	// information
	// le dossier design2D devrait se trouver dans /Library/Application Support/CocOth/design2D
	NSFileManager *fileManager = [[NSFileManager alloc] init];
	
	[fileManager applicationSupportDirectory];
	
	NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
	NSString *folderName = [executableName stringByAppendingPathComponent:@"design 2D"];
	
	
	NSError *error;
	NSString *images2DPath = [[NSFileManager defaultManager]findOrCreateDirectory:NSApplicationSupportDirectory
																		 inDomain:NSUserDomainMask
															  appendPathComponent:folderName
																			error:&error];
	
	//les fichiers/dossiers contenus dans images2DPath			  
	NSArray *files = [fileManager contentsOfDirectoryAtPath:images2DPath error:&error];
	
	[fileManager release];
	
	//creation du sous-menu des designs possibles, marquage du design courant
	NSMenuItem *design2DSubMenuItem=[[menuView submenu] itemWithTag:1];
	NSMenu *design2DMenu=[[NSMenu alloc] init];

	NSString *design2DDefault = [self design2D];

	//le premier item doit etre "default"
	NSMenuItem *design2DItem=[[NSMenuItem alloc] initWithTitle:@"default" action:@selector(setDesign2D:) keyEquivalent:@""];
	[design2DItem setTarget:self];
	[design2DMenu addItem:design2DItem];
	[self setDesign2D:design2DItem];
	[design2DItem release];
	
	for(NSString *folderName in files) {
		
		//supprime .DS_Store
		if([folderName characterAtIndex:0] == '.') {
			continue;
		}
		
		NSMenuItem *design2DItem=[[NSMenuItem alloc] initWithTitle:folderName action:@selector(setDesign2D:) keyEquivalent:@""];
		[design2DItem setTarget:self];
		[design2DMenu addItem:design2DItem];

		if ([folderName isEqual:design2DDefault]) {
			[self setDesign2D:design2DItem];
		}
		
		[design2DItem release];
		
	}
	
	[design2DSubMenuItem setSubmenu:design2DMenu];
	[design2DMenu release];
	
	//show/hide les coordonnées suivant user defaults
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSNumber *showHideFlag = [defaults objectForKey:BC_ShowHideCoord];
	
	if ([showHideFlag boolValue] == YES) {
		[self showHideCoordinated:showHideMenuItem];
	}

	
			
}

- (NSString *)design2D
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	return [defaults objectForKey:BC_design2DKey];
}

	
	

#pragma mark Actions

/*
 fixe le design 2D de l'othellier
 */
- (IBAction)setDesign2D:(id)sender
{
	NSString *nameDesign2D = [sender title];
	
	//load images
	[boardView loadDesign2D:nameDesign2D];
	
	//gestion du marqueur √
	NSMenu *menuOwner = [sender menu];
	NSArray *itemArray = [menuOwner itemArray];
	for(NSMenuItem *item in itemArray)
		[item setState:NSOffState];
	
	[sender setState:NSOnState];
	
	//enregistre la valeur utilisateur
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:nameDesign2D forKey:BC_design2DKey];
	
	
}

/*
 Show/Hide les coordonnées
 */
- (IBAction)showHideCoordinated:(id)sender
{
	
	[boardView showHideCoordinated];

	//enregistre la valeur utilisateur
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

	if([[sender title] isEqual:@"Show Coordinated"]) {
		[sender setTitle:@"Hide Coordinated"];
		[defaults setObject:[NSNumber numberWithBool:YES] forKey:BC_ShowHideCoord];
	} else {
		[sender setTitle:@"Show Coordinated"];
		[defaults setObject:[NSNumber numberWithBool:NO] forKey:BC_ShowHideCoord];

	}
	
}


- (NSString *)nameVariationAtRow:(int)row column:(int)column
{	
	return [appController nameVariation:((row+1)*9 + column+1)];
}

- (NSString *)scoreAtRow:(int)row column:(int)column
{
	return [appController scoreVariation:((row+1)*9 + column+1)];
}

- (void)addVariationAtRow:(int)row column:(int)column
{
	BC_Move *move = [board generateMoveAtRow:row column:column];
	
	if(move) {
		//en informer le browser
		[appController addMove:move];
	}
	
}

- (void)removeVariationAtRow:(int)row column:(int)column
{
	[appController removeVariationAtSquare:((row+1)*9 + column+1)];
}


- (void)setTag:(int)tag atRow:(int)row column:(int)column
{
	[appController setTag:tag atSquare:((row+1)*9 + column+1)];

	[boardView setNeedsDisplay:YES];

}

- (int)tagAtRow:(int)row column:(int)column
{
	return [appController tagAtSquare:((row+1)*9 + column+1)];
}



- (int)discAtRow:(int)row column:(int)column
{
	return [board discAtRow:row column:column];
}

- (int)player
{
	return [board player];
}

- (BOOL)doMoveAtRow:(int)row column:(int)column
{
	BC_Move *move = [board generateMoveAtRow:row column:column];
	
	if(move) {
		//en informer le browser
		[appController addMoveAndPlay:move];
		if ([self shouldPass]) {
			[boardView setNeedsDisplay:YES];
		}

		return YES;
	}
		
	return NO;
}

- (BOOL)isEndgame {
	return [board isEndgame];
}

- (BOOL)shouldPass
{
	if([board shouldPass]) {
		[board doPass];
		if (![board shouldPass]) {
			[board doPass];

			[appController addMoveAndPlay:[[[BC_Move alloc] initWithLocation:PASS] autorelease]];
			return YES;
		}
		//endgame
		[board doPass];
	}
	
	return NO;
}

	

- (BOOL)isLegalAtRow:(int)row column:(int)column
{
	return [board isLegalAtRow:row column:column];
}



- (void)doMove:(BC_Move *)move
{
	[board doMove:move];
	[boardView setNeedsDisplay:YES];
}

- (BOOL)forward
{
	return [appController keyForward];
}

- (void)undoMove:(BC_Move *)move
{
	[board undoMove:move];
	[boardView setNeedsDisplay:YES];

}

- (BOOL)backstep
{
	return [appController keyBackstep];
}

- (void)reset
{
	[board release];
	board = [[BC_Board alloc] init];
	[boardView setNeedsDisplay:YES];
}

- (void)needsDisplay
{
	[boardView setNeedsDisplay:YES];
}

- (NSString *)descriptionForScript
{
	return [board descriptionForScript];
}

- (NSString *)descriptionForZoo
{
	return [board descriptionForZoo];
}

	
- (void)openFile:(NSString *)filename
{
	[appController openFile:filename];
}

/* CocOthAppController ?*/

- (void)tryParseString:(NSString *)pString
{
	[appController tryParseString:pString];
}

- (int)n_empties
{
	return [board n_empties];
}


	

@end
